/*
 * Dialog.java
 *
 * Created on 2004/11/12 +0900
 *
 * $Revision: 59 $
 * $Date: 2008-12-28 19:22:21 +0000 (Sun, 28 Dec 2008) $
 */

package org.gikolet.framework.ui;

import org.gikolet.framework.Toolkit;
import org.gikolet.framework.util.Assert;

/**
 * @author Tetsutaro (latest modification by $Author: tetsutaro.ss $)
 * @version $Revision: 59 $ $Date: 2008-12-28 19:22:21 +0000 (Sun, 28 Dec 2008) $
 */
public class Dialog extends RootControl {
    private String title;
    private boolean modal;

    public Dialog(Display display, boolean modal) {
	this(display, null, modal);
    }

    public Dialog(Display display, String title, boolean modal) {
	this(null, title, modal, false);

	Assert.isNotNull(display);

	setDisplay(display);
    }

    public Dialog(RootControl root, boolean modal) {
	this(root, null, modal, false);
    }

    public Dialog(RootControl root, String title, boolean modal) {
	this(root, title, modal, false);
    }

    public Dialog(RootControl root, String title, boolean modal, boolean focusable) {
	super(root, focusable);

	this.title = title;
	this.modal = modal;

	int it = 2;
	if (this.title != null && !this.title.equals("")) {
	    it += getFont().getHeight() + 2;
	}
	setInsets(it, 2, 2, 2);
	setVisible(false);
    }

    public Dimension getPreferredSize(int hintWidth, int hintHeight) {
	Dimension ps = super.getPreferredSize(hintWidth, hintHeight);
	if (title != null) {
	    int tw = getFont().stringWidth(title);
	    tw = getLeftInset() + tw + getRightInset();

	    ps.setWidth(Math.max(ps.getWidth(), tw));
	}
	return ps;
    }

    public boolean isModal() {
	return this.modal;
    }

    protected void paintWidget(Graphics g) {
	Font font = g.getFont();
	g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
	if (this.title != null) {
	    g.drawString(this.title, 2, 2);
	    g.drawLine(1, 2 + font.getHeight(), getWidth() - 2, 2 + font.getHeight());
	}
    }

    public String getTitle() {
	return this.title;
    }

    protected void firePropertyChanged(String propertyName) {
	if (PROPERTY_FONT.equals(propertyName)) {
	    int it = 2;
	    if (this.title != null) {
		it += getFont().getHeight() + 2;
	    }
	    setInsets(it, 2, 2, 2);

	} else if (PROPERTY_VISIBLE.equals(propertyName)) {
	    Display display = getDisplay();
	    if (display != null) {
		if (isVisible()) {
		    display.addDialog(this);
		    revalidate();
		    repaint();
		} else {
		    display.removeDialog(this);
		    display.repaint(getX(), getY(), getWidth(), getHeight());
		}

		if (isModal()) {
		    if (isVisible()) {
			Toolkit.getRequestProcesser().startRequest();
		    } else {
			Toolkit.getRequestProcesser().stopRequest();
		    }
		}
	    }
	}

	super.firePropertyChanged(propertyName);
    }
}
